const Controller = require('egg').Controller

const errRes = {
  code: 500,
  data: null,
  msg: '错误信息',
}

// 默认头像，放在 user.js 的最外，部避免重复声明。
const defaultAvatar =
  'http://s.yezgea02.com/1615973940679/WeChat77d6d2ac093e247c361f0b8a7aeb6c2a.png'

class UserController extends Controller {
  /**
   * 注册新用户
   * @returns user
   */
  async register() {
    const { ctx } = this
    const { username, password } = ctx.request.body
    if (!username || !password) {
      ctx.body = Object.assign(errRes, { msg: '账号密码不能为空' })
      return
    } else {
      const userInfo = await ctx.service.user.findUserByName(username)
      if (userInfo && userInfo.id) {
        ctx.body = Object.assign(errRes, {
          msg: '账户名称已被注册，请重新输入',
        })
        return
      } else {
        const newUser = {
          username,
          password,
          avater: defaultAvatar,
          signature: '时间精算师',
          ctime: new Date().getTime(),
        }

        const result = await ctx.service.user.register(newUser)
        if (result) {
          ctx.body = {
            code: 200,
            msg: '注册成功',
            data: null,
          }
        } else {
          ctx.body = Obejct.assign(errRes, {
            msg: '注册失败',
          })
        }
      }
    }
  }

  /**
   * 用户登录
   */
  async login() {
    const { ctx, app } = this

    const { username, password } = ctx.request.body
    if (!username || !password) {
      ctx.body = Object.assign(errRes, { msg: '请输入账号密码' })
      return
    } else {
      const userInfo = await ctx.service.user.findUserByName(username)
      // console.log(userInfo)

      if (!userInfo || !userInfo.id) {
        ctx.body = Object.assign(errRes, {
          msg: '账号不存在',
        })
        return
      } else {
        if (userInfo.password !== password) {
          ctx.body = Object.assign(errRes, {
            msg: '密码不正确',
          })
          return
        } else {
          // 登录成功 返回 token
          const token = app.jwt.sign(
            {
              id: userInfo.id,
              username: userInfo.username,
              exp: Math.floor(Date.now() / 1000) + 24 * 60 * 60,
            },
            app.config.jwt.secret
          )

          ctx.body = {
            code: 200,
            msg: '登录成功',
            data: {
              token,
            },
          }
        }
      }
    }
  }

  async decodeToken() {
    const { ctx, app } = this
    const token = ctx.request.header.authorization
    try {
      const decode = app.jwt.verify(token, app.config.jwt.secret)
      ctx.body = {
        code: 200,
        msg: 'ok',
        data: {
          ...decode,
        },
      }
    } catch (error) {
      ctx.body = errRes
    }
  }
  /**
   * 登录用户获取 个人用户信息
   */
  async getUserInfo() {
    const { ctx, app } = this
    const token = ctx.request.header.authorization
    const decode = app.jwt.verify(token, app.config.jwt.secret)
    const userInfo = await ctx.service.user.findUserByName(decode.username)
    ctx.body = {
      code: 200,
      msg: '请求成功',
      data: {
        id: userInfo.id,
        username: userInfo.username,
        avater: userInfo.avater || defaultAvatar,
        signature: userInfo.signature || '',
      },
    }
  }
  /**
   * 登录用户修改 用户个人信息（签名，头像）
   */
  async editUserInfo() {
    const { ctx, app } = this
    const { signature, avater } = ctx.request.body
    const token = ctx.request.header.authorization
    const decode = app.jwt.verify(token, app.config.jwt.secret)
    if (!decode) return
    const userInfo = await ctx.service.user.findUserByName(decode.username)
    const result = await ctx.service.user.editUserInfo({
      ...userInfo,
      signature,
      avater,
    })
    if (result) {
      ctx.body = {
        code: 200,
        msg: '编辑成功',
        data: {
          ...userInfo,
          signature,
          avater,
        },
      }
    }
  }

  async modifyPassword() {
    const { ctx, app } = this
    const { old_pass, new_pass } = ctx.request.body
    const token = ctx.request.header.authorization
    const decode = app.jwt.verify(token, app.config.jwt.secret)
    if (!decode || !decode.id) return

    try {
      const user = await ctx.service.user.findUserByName(decode.username)
      if (!user) return
      // console.log('modifyPassword', user)
      // console.log('modifyPassword', old_pass)
      if (user.password != old_pass) {
        ctx.body = {
          code: 400,
          msg: '旧密码不正确',
          data: null,
        }
        return
      }

      const result = await ctx.service.user.editUserInfo({
        ...user,
        password: new_pass,
      })
      if (result) {
        ctx.body = {
          code: 200,
          msg: '修改成功',
          data: null,
        }
      }
    } catch (error) {
      console.log('modify password error', error)
      ctx.body = {
        code: 500,
        msg: '系统错误',
        data: null,
      }
    }
  }
}

module.exports = UserController
